<?php
defined('SYSPATH') OR die('No direct access allowed.');
/**
 * user.php
 * @author ranuandra
 *
 * 19 Agu 2011 10:24:31
 *
 * 
 */

class Controller_User extends Kohana_Mapi
{
	public function action_index()
	{
		
	}
	
	public function action_view()
	{
		$this->auto_render = false;

		$user = ORM::factory('user')->find_all()->as_array();
		$hasil = array();
		foreach($user as $data)
		{
			$datas = array(
							'id' 		=> $data->id,
							'username'	=> $data->username,
							'email'		=> $data->email,
							'password'	=> $data->password,
						);
			$hasil[] = $datas;
		}
		echo json_encode(array("success" => true, "message" => "Loaded data", "user" => $hasil));		
		
	}
	
	public function action_save()
	{
		$this->auto_render = false;
		try {
		//$post = Validation::factory($_POST);
			$users = ORM::factory('user');
			$users->create_user($_POST, array(
			 									'username',
												'password',
			 									'email',
			  					));
			
	  		$login_role = new Model_Role(array('name' =>'login'));
			$users->add('roles',$login_role);
			if($_POST['type'] == '1')
			{
		  		$login_role = new Model_Role(array('name' =>'user'));
				$users->add('roles',$login_role);				
			}
			else 
			{
		  		$login_role = new Model_Role(array('name' =>'admin'));
				$users->add('roles',$login_role);					
			}
			
			echo json_encode(array("success" => true, "message" => "Data Berhasil Disimpan"));


		}
		catch(ORM_Validation_Exception $e)
		{
			$errors = $e->errors('models');
			echo json_encode(array("success" => false, "message" => "Terjadi kesalahan silahkan di perbaiki", "errors" => $errors));
			//$errors = $e->errors('models');
			//print_r($errors);
		}		
	
	}
}